import { DefineComponent, defineComponent, onMounted, PropType, reactive, Ref, ref } from 'vue';
import { Tabs, TabPane } from 'ant-design-vue';
import { Panes, PaneInfo, ErrorChildId, BaseDefineComponent } from '@/domain/dataBoard/types/common';
import { Key } from 'ant-design-vue/lib/vc-table/interface';

export default defineComponent({
  name: 'customTap',
  props: {
    slot: {
      type: Object as PropType<{
        default: BaseDefineComponent;
      }>,
      default: () => {}
    }
  },
  setup(props, { slots }) {
    const newTabIndex = ref(0);
    const add = (title: string, childId: number) => {
      const keyName: string | undefined = Object.keys(panes).find((v) => panes[v].title === title && panes[v].childId === childId);
      // 重复处理
      if (keyName) {
        activeKey.value = keyName;
        return;
      }
      const newIdx = newTabIndex.value++;
      const key = `tab${newIdx}`;
      activeKey.value = key;
      panes[key] = { title, content: <props.slot.default add={add} childId={childId}></props.slot.default>, key: key, closable: true, childId };
    };
    const panes: Panes = reactive({
      tap0: { title: '全部', content: <props.slot.default add={add}></props.slot.default>, key: 'tap0', closable: false }
    });
    const activeKey = ref(panes[Object.keys(panes)[0]].key);

    const onEdit = (targetKey: unknown, action: 'add' | 'remove') => {
      if (action === 'remove') {
        if ((targetKey as string | MouseEvent) === activeKey.value) {
          Object.keys(panes).forEach((item, index) => {
            if (item === activeKey.value) {
              let nextActiveIndex = index > 0 ? index - 1 : 0;
              activeKey.value = panes[Object.keys(panes)[nextActiveIndex]].key;
            }
          });
        }

        delete panes[targetKey as string];
      }
    };
    const onChange = (targetKey: Partial<Key>) => {
      activeKey.value = targetKey as string;
    };

    onMounted(() => {});

    return () => (
      <Tabs
        class={'card-container relative top-3 w-full h-full'}
        type="editable-card"
        onEdit={onEdit}
        hideAdd={true}
        activeKey={activeKey.value}
        onChange={onChange}
      >
        {Object.keys(panes).map((key) => (
          <TabPane class="w-full h-full overflow-auto " tab={panes[key].title} key={panes[key].key} closable={panes[key].closable}>
            <div class={'pl-5 pr-5 h-full bg-white'}>{panes[key].content} </div>
          </TabPane>
        ))}
      </Tabs>
    );
  }
});
